<template>
  <div>
    <Editor
      :id="tinymceId"
      v-model="tinymceHtml"
      :init="init"
      :disabled="disabled"
    ></Editor>

    <el-dialog
      title="图片素材"
      :visible.sync="dialogVisible"
      width="80%"
      :before-close="handleClose"
    >

      <div>
        <el-upload
          class="upload-demo"
          action
          :http-request="handleUploadFile"
          :with-credentials='true'
          :on-success="successUpload"
          multiple
          :limit="3"
          :file-list="fileList"
          :show-file-list="false"
        >
          <el-button
            size="small"
            type="primary"
            data-title="点击上传"
          >点击上传</el-button>
          <div
            slot="tip"
            class="el-upload__tip"
          >只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>
      </div>

      <el-divider></el-divider>

      <div
        class="productPicList"
        v-loading="picListLoading"
      >

        <div
          v-for="(item,index) in imgList"
          class="item"
        >
          <el-image
            :src="baseUrl+item.product_pic_path"
            fit="scale-down"
            :preview-src-list="previewList"
          >

          </el-image>

          <el-row>
            <el-col :span="24">
              <el-checkbox
                v-model="item._id"
                @change="checkPic(item.product_pic_path)"
              >选择</el-checkbox>

            </el-col>

            <el-col
              :span="24"
              centent
            >
              <el-button
                type="text"
                @click="delPic(item._id)"
              >
                删除
              </el-button>
            </el-col>
          </el-row>

        </div>

      </div>

      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="dialogVisible = false"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>


<script>
import tinymce from 'tinymce/tinymce' //tinymce默认hidden，
import Editor from '@tinymce/tinymce-vue' //编辑器引入
import 'tinymce/themes/silver/theme' //编辑器主题
import 'tinymce/icons/default' //引入编辑器图标icon
import 'tinymce/models/dom'

import 'tinymce/plugins/link' //超链接
import 'tinymce/plugins/image' //插入编辑图片
import 'tinymce/plugins/lists' //列表插件
import 'tinymce/plugins/charmap' //特殊字符
import 'tinymce/plugins/media' //插入编辑媒体
import 'tinymce/plugins/wordcount' // 字数统计
import 'tinymce/plugins/table'

import 'tinymce/plugins/advlist'
import 'tinymce/plugins/autolink'
import 'tinymce/plugins/fullscreen'
import 'tinymce/plugins/preview'

import { getProductPic, uploadProductPic, getProductEditor } from '@/api/business/product'

export default {
  name: "index",
  props: {
    //tinyvalue首先在父组件中定义，用于向本子组件mytinymce发送数据
    //然后在这里声明，用于本子组件接收父组件数据
    tinyvalue: {
      type: String,
      default: ''
    },
    //是否禁用
    disabled: {
      type: Boolean,
      default: false,
    },
    //插件
    plugins: {
      type: [String, Array],
      default: 'advlist autolink lists charmap table fullscreen imagetools preview',
    },
    //工具栏
    toolbar: {
      type: [String, Array],
      default:
        'undo redo |  formatselect | forecolor backcolor bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent lists image | fullscreen | preview | mybutton',
    },
  },
  data () {
    return {
      dialogVisible: false,
      picListLoading: false,
      fileList: [],
      imgList: [],          // 图片素材缩略图列表
      previewList: [],      // 图片素材放大缩略图数据列表
      productId: this.$route.query.productId,
      baseUrl: this.$baseUrl,
      checkPicUrl: '',      // 选中的图片路径
      myImg: '',
      tinymceHtml: this.tinyvalue,

      tinymceId: '',
      init: {
        selector: '#tinymce',
        language_url: './tinymce/langs/zh_CN.js', //汉化路径是自定义的
        language: 'zh_CN',
        skin_url: '/tinymce/skins/ui/oxide', //皮肤
        plugins: this.plugins, //插件
        //工具栏
        toolbar: this.toolbar,
        toolbar_location: '/',
        fontsize_formats: '12px 14px 16px 18px 20px 22px 24px 28px 32px 36px 48px 56px 72px', //字体大小
        height: 500, //高度
        placeholder: '商品详情（可输入图片详情、文字详情、表格详情）',
        paste_data_images: false,
        image_dimensions: false,
        content_style: 'img{width:100%;height:auto;  display:block} ',
        // 自定义图片上传
        images_upload_handler: (blobInfo, success, failure) => {
          // const formData = new FormData()
          // formData.append('file', blobInfo.blob())
          // //使用自己接口或者axios
          // goodsAlbumFilesUploadImage(formData).then(res => {
          //     console.log(res.code)
          //     if (res.code == 200) {
          //         let file = res.data.url
          //         success(file)
          //         return
          //     }
          //     failure('上传失败')
          // }).catch(error => {
          //     console.log(error)
          //     failure('上传出错')
          // })
          const img = this.myImg
          success(img)
        },
        branding: false, //隐藏右下角技术支持
        paste_preprocess: function (plugin, args) {
          var pattern = /(?<=(img src="))/
          if (pattern.test(args.content)) {
            args.content = '';
            console.log("不能粘贴图片");
          }
        },
        setup: (editor) => {
          editor.ui.registry.addButton('mybutton', {
            text: '插入图片', onAction: () => {
              this.getProductPic()
              this.dialogVisible = true
            }
          })
        }
      }
    }
  },
  components: { Editor },
  // 生命周期 - 创建完成（访问当前this实例）
  created () {

  },
  // //监听内容变化
  // value (newValue) {
  //   this.myValue = newValue || ''
  // },
  watch: {
    //监听内容变化，用于辅助父子组件之间的通讯
    tinyvalue (newValue) {
      //tinyvalue是父组件代理人，父组件值一旦变化，推送给子组件
      this.tinymceHtml = newValue;
    },
    tinymceHtml (newValue) {
      //tinymceHtml是子组件的值，如果改变，直接反馈给父组件
      //   tinymceinput是父组件中的用于接收子组件的事件（名称写死，用于后面调用）
      this.$emit("tinymceinput", newValue);
    },
  },
  // 生命周期 - 挂载完成（访问DOM元素）
  mounted () {
    tinymce.init({})
    // this.getProductPic()
    this.getProductEditor()
  },
  // 函数
  methods: {
    async getProductEditor () { // 获取商品富文本内容
      const query = { productId: this.productId }
      await getProductEditor(query).then(response => {
        this.tinymceHtml = response.data.data
      })
    },
    async handleUploadFile (params) { // 重写上传方法
      const file = params.file
      // 使用FormData传参数和文件
      // 根据后台需求数据格式
      const form = new FormData();
      // 文件对象
      form.append("product_pic", file);
      form.append("productId", this.productId)
      // console.log("product_pic => ", form.get("product_pic"))
      // console.log("productId => ", form.get("productId"))
      await uploadProductPic(form).then(res => {
        if (res.data.msg == "操作成功") {
          this.$message({
            message: res.data.msg,
            type: 'success'
          });
        }
      })
    },
    successUpload () {  // 上传成功
      this.getProductPic()
    },
    getProductPic () {  // 获取图片素材
      this.picListLoading = true
      const query = { productId: this.productId }
      getProductPic(query).then(response => {
        this.imgList = response.data.data      // 图片缩略图组
        for (var i in this.imgList) {
          this.previewList[i] = this.$baseUrl + this.imgList[i].product_pic_path  // 放大图片组
        }
        this.picListLoading = false
      })
    },
    delPic (value) { // 删除商品图片素材里的图片
      // console.log("delPic => value", value)
      const data = { picId: value }
      // delProductPic(data).then(res => {
      //   if (res.data.msg == "操作成功") {
      //     this.$message({
      //       type: 'success',
      //       message: '删除成功!'
      //     })
      //   } else {
      //     this.$message.error(res.data.msg)
      //   }
      //   this.getProductPic()
      // })

    },
    checkPic (value) { // 选择图片
      console.log("checkPic => value", value)
      this.dialogVisible = false
      this.checkPicUrl = value
      this.myImg = value
      this.select()
    },
    handleClose (done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => { });
    },
    select (success) {
      if (!this.tinymceHtml) {
        this.tinymceHtml = `<img src="${this.baseUrl}${this.myImg}">`
      } else {
        this.tinymceHtml = `<img src="${this.baseUrl}${this.myImg}">` + this.tinymceHtml
      }
    }
  }
}
</script>

<style lang="scss" scoped>
/* @import url(); 引入css类 */
.index {
}

.productPicList {
  display: grid;
  // grid-template-columns: 1fr 1fr 1fr 1fr 1fr 1fr;
  grid-template-columns: repeat(6, 6fr);
  gap: 1rem;
  // background: #f5f5f5;
  .item {
    width: 100%;
    height: 100%;
    box-shadow: 0 5px 15px rgba(188, 186, 186, 0.3);
    // transition: box-shadow 0.5s ease, transform 0.2s ease;
    // &:hover {
    //   box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
    // }
    .el-image {
      height: 150px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .el-row .el-col {
      margin-top: 5px;
      display: flex;
      justify-content: center; /*主轴上居中*/
      align-items: center; /*侧轴上居中*/
    }
  }
}
</style>